//
//  ChatViewController+Data.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2020/2/17.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON
import SwiftyJSON
import AVFoundation

extension ChatViewController {
    func loadData() {
        HUDTool.showActivity()
        ChatViewModel.getChatRecord(diagnoseId: diagnoseId, current: current, success: { models in
            HUDTool.hideActivity()
            self.viewModel = ChatViewModel(msgModels: models.sorted(by: { (Double($0.sendTime ?? "") ?? 0) > (Double($1.sendTime ?? "") ?? 0)}))
            switch self.status {
            case .nurse:
                self.loadNurseInfo()
            case .advisory:
                self.loadPatientInfo()
            case .none:
                self.loadPatientInfo()
            }
            
        }) { errorMsg in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    func loadPatientInfo() {
        AdvisoryDetailViewModel.getPatientAdvisoryDetail(target: ApiManager.advisotyDetail(paras: ["diagnoseId":diagnoseId]) , success: { model in
            self.detailVM = AdvisoryDetailViewModel(detail: model)
            self.detailVM?.saveDoctorPic()
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
        }
    }
    
    func loadNurseInfo() {
        AdvisoryDetailViewModel.getPatientAdvisoryDetail(target: ApiManager.nurseDetail(paras: ["diagnoseId":diagnoseId]) , success: { model in
            self.detailVM = AdvisoryDetailViewModel(detail: model)
            self.detailVM?.saveDoctorPic()
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
        }
    }
    
    
    func refreshChatRecord() {
        ChatViewModel.getChatRecord(diagnoseId: diagnoseId, current: current, success: { models in
            self.viewModel = ChatViewModel(msgModels: models.reversed())
            self.tableView.reloadData()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
                self.tableView.scrollBottomToLastRow()
            }
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc func loadLastMsg() {
        guard let vm = viewModel, vm.numberOfRows > 0 else { return }
        current += 1
        ChatViewModel.getChatRecord(diagnoseId: diagnoseId, current: current, success: { models in
            self.tableView.mj_header?.endRefreshing()
            
            if models.count == 0 { self.current -= 1 }
            
            if self.detailVM?.diagType == .advisory {
                let first = vm.removeFirst()
                self.viewModel?.insert(models: models.reversed(), isBottom: false)
                self.viewModel?.insert(msgModel: first, isBottom: false)
            } else {
                self.viewModel?.insert(models: models.reversed(), isBottom: false)
            }
            
            self.tableView.reloadData()
        }) { errorMsg in
            self.current -= 1
            self.tableView.mj_header?.endRefreshing()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc func sendMessageFail(_ noti: Notification) {
        if let model = noti.object as? ChatMsgModel, let vm = viewModel, !waitSendMsgs.isEmpty {
            if waitSendMsgs.first!.clientId == model.clientId {
                var model = vm.msgModels[vm.numberOfRows - waitSendMsgs.count]
                model.isSendSuccess = false
                model.isSending = false
                vm.msgModels[vm.numberOfRows - waitSendMsgs.count] = model
                waitSendMsgs.removeFirst()
                tableView.reloadData()
            }
        }
    }
    
    @objc func receiveMessage(_ noti: Notification) {
        guard let message = noti.object as? String,
              let receiveModel = JSONDeserializer<ReceiveModel>.deserializeFrom(json: message) else { return }
        
        if receiveModel.command == 12 {
            if let vm = viewModel, !waitSendMsgs.isEmpty {
                var model = vm.msgModels[vm.numberOfRows - waitSendMsgs.count]
                model.isSendSuccess = true
                model.isSending = false
                vm.msgModels[vm.numberOfRows - waitSendMsgs.count] = model
                waitSendMsgs.removeFirst()
                tableView.reloadData()
            }
            
        }
        
        // 防止非本诊断消息插入到当前消息中
        // 为什么写的这么复杂？
        // 数据tm格式有两种
        if receiveModel.cmd == -1 {
            if "\(receiveModel.data?.diagnoseId ?? 0)" != diagnoseId {
                return
            }
        } else {
            if "\(receiveModel.diagnoseId)" != diagnoseId {
                return
            }
        }
      
        if receiveModel.command == 11 {
            
            guard let model = receiveModel.data else { return }
            
            guard let vm = viewModel, let detailVm = detailVM else { return }
            
            // 处方消息
            if model.msgType == 6 {
                dealWithPrescriptionMessage(model: model)
                return
            }
            
            let msgModel = ChatMsgModel(
                sendTime: Date().toString(format: "HH:mm"),
                fromType: model.roleType,
                messageId: model.id,
                content: model.content,
                messageType: model.msgType,
                src: model.src,
                time: model.time,
                prescription: model.prescription
            )
            
            vm.insert(msgModel: msgModel)
            let insertIndexPath = IndexPath(row: vm.numberOfRows - 1,
                                            section: tableView.numberOfSections - 1)
            tableView.insertRowsAtBottom([insertIndexPath])
            
            WebSocketManager.shared().readMsgToServer(detailVm, model: model)
            
        } else if receiveModel.command == 20 {
            
            guard let vm = viewModel, let detailVm = detailVM else { return }
            
            let json = JSON(parseJSON: message)
            if let models = JSONDeserializer<ReceiveModel.MsgModel>.deserializeModelArrayFrom(json: json["data"]["friends"][detailVm.chatReceiveId].description) as? [ReceiveModel.MsgModel] {
                models.forEach {
                    if $0.cmd == 11 {
                        if $0.msgType == 6 {
                            self.dealWithPrescriptionMessage(model: $0)
                        } else {
                            let msgModel = ChatMsgModel(
                                sendTime: Date().toString(format: "HH:mm"),
                                fromType: $0.roleType,
                                messageId: $0.id,
                                content: $0.content,
                                messageType: $0.msgType,
                                src: $0.src,
                                prescription: $0.prescription
                            )
                            vm.insert(msgModel: msgModel)
                            let insertIndexPath = IndexPath(row: vm.numberOfRows - 1,
                                                            section: tableView.numberOfSections - 1)
                            tableView.insertRowsAtBottom([insertIndexPath])
                        }
                    }
                }
            }
        }
        
        /// 108-医生接受图文咨询  110-处方撤回 208-护士接受护理咨询
        if receiveModel.cmd == 108 ||
            receiveModel.cmd == 208 ||
            receiveModel.cmd == 110 {
            loadData()
        }
        
        /// 医生拒绝图文咨询
        if receiveModel.cmd == 109 {
            navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func sureEndAdvisory(_ noti: Notification) {
        let vc = MyAdvisoryOrderFinishController(with: diagnoseId)
        removeCurrentVcWhenPush(vc)
    }
    
    @objc func audioPlayBegin(_ noti: Notification) {
        guard let vm = viewModel, let index = vm.playingIndexPath else {
            return
        }
        UIDevice.current.isProximityMonitoringEnabled = true
        var msgModel = vm.msgModels[vm.numberOfRows - index]
        msgModel.isPlaying = true
        vm.msgModels[vm.numberOfRows - index] = msgModel
        viewModel = vm
        tableView.reloadData()
    }
    
    @objc func audioPalyEnd(_ noti: Notification) {
        guard let vm = viewModel, let index = vm.playingIndexPath else {
            return
        }
        UIDevice.current.isProximityMonitoringEnabled = false
        var msgModel = vm.msgModels[vm.numberOfRows - index]
        msgModel.isPlaying = false
        vm.msgModels[vm.numberOfRows - index] = msgModel
        vm.playingIndexPath = nil
        viewModel = vm
        tableView.reloadData()
    }
    
    @objc func sensorStateChange(_ noti: Notification) {
        if UIDevice.current.proximityState == true {
            print("Device is close to user")
            try? AVAudioSession.sharedInstance().setCategory(.playAndRecord)
        } else {
            print("Device is not close to user")
            try? AVAudioSession.sharedInstance().setCategory(.playback)
        }
    }
    
    private func showAlert(_ model: ReceiveModel.MsgModel) {
        AlertTool.showAlert(self,
                            message: "医生已出具诊断意见，若您没有其它问题，请确认是否结束问诊?",
                            sureTitle: "确认结束",
                            cancelTitle: "继续咨询",
                            type: .double,
                            sureHandler:
        { _ in
            self.endAdvisory(model, isSure: 1)
        }) { _ in
            self.endAdvisory(model, isSure: 0)
        }
    }
    
    /// 结束图文咨询
    private func endAdvisory(_ model: ReceiveModel.MsgModel, isSure: Int) {
        let sure = isSure
        AdvisoryViewModel.endAdvisory(doctorId: "\(model.from)",
                                      diagnoseId: "\(model.diagnoseId)",
                                      isSure: isSure)
        { (errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.show(message: errorMsg)
            case .success:
                if sure == 1 {
                    HUDTool.show(message: "已结束图文咨询")
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
    
    /// 插入处方消息
    private func dealWithPrescriptionMessage(model: ReceiveModel.MsgModel) {
        guard let detailVM = detailVM,
        let viewModel = viewModel else { return }
        ChatViewModel.queryPrescriptionMsg(prescriptionId: model.preId, success: { m in
            let msgModel = ChatMsgModel(
                sendTime: Date().toString(format: "HH:mm"),
                fromType: model.roleType,
                messageId: model.id,
                content: model.content,
                messageType: model.msgType,
                src: model.src,
                prescription: m
            )
            viewModel.insert(msgModel: msgModel)
            let insertIndexPath = IndexPath(row: viewModel.numberOfRows - 1,
                                            section: self.tableView.numberOfSections - 1)
            self.tableView.insertRowsAtBottom([insertIndexPath])
            
            WebSocketManager.shared().readMsgToServer(detailVM, model: model)
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
        }
    }
}
